package com.syqc.comlib.utils

import com.google.gson.Gson
import com.google.gson.JsonParser
import com.google.gson.reflect.TypeToken

/**
 *@Author Jasper
 *@Time   2020/7/21
 *@Desc   todo
 */
object GsonUtil {
    val gson = Gson()

    inline fun <reified T> formObject(json: String?): T {
        return gson.fromJson(json, T::class.java)
    }

    fun <T> formArrayList(json: String?, clazz: Class<T>): ArrayList<T> {
        val asJsonArray = JsonParser.parseString(json).asJsonArray
        val list = ArrayList<T>()
        for (jsonElement in asJsonArray) {
            list.add(gson.fromJson(jsonElement, clazz))
        }
        return list
    }


    fun formArrayStr(json: String): ArrayList<String> {
        val asJsonArray = JsonParser.parseString(json).asJsonArray
        val list = ArrayList<String>()
        for (jsonElement in asJsonArray) {
            list.add(jsonElement.toString())
        }
        return list
    }

    fun <T> toJson(t: T): String {
        return gson.toJson(t)
    }

    fun formJsonMap(json: String): Map<String, Any> {
        val type = object : TypeToken<Map<String, Any>>() {}.type
        return gson.fromJson(json, type)
    }

    fun formJsonStrMap(json: String): Map<String, String> {
        val type = object : TypeToken<Map<String, String>>() {}.type
        return gson.fromJson(json, type)
    }
}


